<?php
namespace App\Http\Controllers\Home;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;
class CustomController extends Controller{
    function __construct() {
        $this->appid  = getenv('APPID');
        $this->secret = getenv('AppSecret');
    }
    
   //消息推送
    public function customInfo(Request $res){
        if(isset($_GET['echostr'])){
            if($this->checkSignature()){
                return $_GET['echostr'];
            }
        }else{
            /*  消息推送 数据格式 JSON  */
//            $this->responseMsg(); //未转发，直接回复用户
            $this->transmitMsg(); //转发消息到微信在线客服工具
              
           /*消息推送   数据格式  xml */   
//            $this->responseXml();  没有写完
        }
        
    }
    
    public function checkSignature(){
        $signature = trim($_GET['signature']);
        $timestamp = trim($_GET['timestamp']);
        $nonce =trim($_GET['nonce']);
        //$token = getenv('TOKEN');
        $token = 'laravel';
        $tmpArr = array($token, $timestamp, $nonce);
        sort($tmpArr, SORT_STRING);
        $tmpStr = implode( $tmpArr );
        $tmpStr = sha1( $tmpStr );
        if( $tmpStr == $signature ){
            return true;
        }else{
            return false;
        }
    }
    
    //发送客服消息,不转发到网页版客服工具
    public function responseMsg(){
       $postStr = $GLOBALS["HTTP_RAW_POST_DATA"];
        if (!empty($postStr) && is_string($postStr)){
            //禁止引用外部xml实体
            //libxml_disable_entity_loader(true);
            //$postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
            $postArr = json_decode($postStr,true); //加上true后，转化为数组，否则为json
            if($postArr['FromUserName']){
                $fromUsername = $postArr['FromUserName'];   //发送者openid
            }
            if(!empty($postArr['MsgType']) && $postArr['MsgType'] == 'text'){   //文本消息
                $content = '您好，有什么能帮助你?';
                $data=array(
                    "touser"=>$fromUsername,
                    "msgtype"=>"text",
                    "text"=>array("content"=>$content)
                );
                $json = json_encode($data,JSON_UNESCAPED_UNICODE);  //php5.4+
            }elseif(!empty($postArr['MsgType']) && $postArr['MsgType'] == 'image'){ //图文消息
                $mediaId = $postArr['MediaId'];   	//图片消息媒体id
                $data1=array( //发送图文链接
                    "touser"=>$fromUsername,
                    "msgtype"=>"link",
                    "link"=>array(
                           "title"=>"Happy Day",
                           "description"=>"Is Really A Happy Day", 
                           "url"=> $_SERVER['SERVER_NAME'].'/uploads/photo/XAXHpN55rT0hWW3pzDPOLvmxRbAXEMwskIUZBuDM.jpeg'
//                         "thumb_url"=> "THUMB_URL"
                            )
                );
                
                //发送图片消息,此处返回用户发来的图片
                $data = array(
                    "touser"=>$fromUsername,
                    "msgtype"=>"image",
                    "image"=>array("media_id"=>$mediaId)
                );
                
                $json = json_encode($data,JSON_UNESCAPED_UNICODE);                
            }elseif($postArr['MsgType'] == 'event' && $postArr['Event']=='user_enter_tempsession'){ //进入客服动作
                $content = '您好，EAI客服为您服务';
                $data=array(
                    "touser"=>$fromUsername,
                    "msgtype"=>"text",
                    "text"=>array("content"=>$content)
                );
                $json = json_encode($data,JSON_UNESCAPED_UNICODE);  //php5.4+
                
            }else{ //小程序卡片功能没有做
                exit('aaa');
            }
            $access_token = getWxToken();
            $url = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=".$access_token;
            $this->sendCustomMsgApi($url,$json);
            $this->customInputStatus($fromUsername,$access_token);
        }else{
            echo "";
            exit;
        }
    }
    
    //将消息转发到网页版客服工具
    public function transmitMsg(){
        $postMsg = $GLOBALS["HTTP_RAW_POST_DATA"]; //此处只能用这个获取
        if(!empty($postMsg) && is_string($postMsg)){
            $postMsg = json_decode($postMsg,true);
            $toOpenId = $postMsg['FromUserName']; //接收方帐号（收到的OpenID）
            $fromOpenId = $postMsg['ToUserName']; //开发者微信号
            $data = array(
                'ToUserName'  =>$toOpenId,
                'FromUserName'=>$fromOpenId,
                'CreateTime'  =>time(),
                'MsgType'     =>'transfer_customer_service'
            );
            $access_token = getWxToken();
            $this->customInputStatus($toOpenId,$access_token);
            exit(json_encode($data));
        }
    }
    
    /*
        发送客服消息
     * @param json $json
     * @author [zhaoruijuan]
     * @since 2017-12-13
    */
    public function sendCustomMsgApi($url,$json){
        
        //以'json'格式发送post的https请求
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_POST, 1); // 发送一个常规的Post请求
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        if (!empty($json)){
            curl_setopt($curl, CURLOPT_POSTFIELDS,$json);
        }
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        //curl_setopt($curl, CURLOPT_HTTPHEADER, $headers );
        $output = curl_exec($curl);
        Storage::put('res.txt',$output);
        if (curl_errno($curl)) {
            echo 'Errno'.curl_error($curl);//捕抓异常
        }
        curl_close($curl);
        if($output == 0){
            echo 'success';exit;
        }
    }
    
    //头像上传
    public function uploadFile(Request $res){
        $file = $res->file('avatar');
        if(!$file->isValid()){  //检测上传是否有效  
            return json_encode(array('msg' => '上传失败','status'=>0));
        } 
        $extensionArray = array('jpg','png','gif','jpeg');
        if(!in_array($file->getClientOriginalExtension(), $extensionArray) ){
            return json_encode(array('status'=>0,'msg'=>'不允许的扩展名'));
        }
        $destinationPath = '/photo';
        $path = $file->store($destinationPath,'uploadsimage');
        return json_encode(array('status'=>1,'msg'=>'上传成功','url'=>$path));
    }
    
    
    //回复客服消息  消息推送 数据格式为 xml格式
    public function responseXml(){
        
    }
    
    
    //客服输入状态
    public function customInputStatus($fromUsername,$access_token){
        $inputStatus = 'https://api.weixin.qq.com/cgi-bin/message/custom/typing?access_token='.$access_token;
        $status = array('touser'=>$fromUsername,'command'=>'Typing');
        $inputData = json_encode($status,JSON_UNESCAPED_UNICODE);
        $returnStatus = $this->sendCustomMsgApi($inputStatus,$inputData);
        Storage::put('return.txt',$returnStatus);
    }
    
    
    //下载文件
    public function downloadFile(Request $res){
        $userid = intval($res->get('userid'));
        if($userid != 0){
           $photo = DB::table('waihui_member')->where('id',$userid)->value('photo');
           if(strpos($photo,'http://') !== 0){
               $photo = 'https://www.eaifx.com'.$photo;
           }
           return json_encode(array('url'=>$photo));
        }
    }
    
    
}


